package com.topcheer.gateway.ribbon;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author xutao
 * @Package com.topcheer.common.base.loadBalance
 * @Description: 平滑加权轮训算法
 * 每个地址有权重、当前权重
 * 1 初始化当前权重为0
 * 2 当前权重=当前权重+权重
 * 3 找到当前权重值最大的  并将当前权重减去总权重值
 * 4 返回该ip
 * @date 2020/4/10 16:48
 */
public class WeightRoundRibbon {

    public WeightServer getServer(List<WeightServer> serverList) {
        Integer totalWeight = serverList.stream().mapToInt(WeightServer::getWeight).sum();
        for (WeightServer weight : serverList) {
            weight.setCurrentWeight(weight.getCurrentWeight() + weight.getWeight());
        }
        Optional<WeightServer> first =
            serverList.stream().sorted(Comparator.comparingInt(WeightServer::getCurrentWeight).reversed()).findFirst();
        if (first.isPresent()) {
            WeightServer weight = first.get();
            weight.setCurrentWeight(weight.getCurrentWeight() - totalWeight);
            return weight;
        }
        return serverList.get(0);

    }

}


